/**
 * Created by wry on 2015/4/13.
 */
angular.module('backofficeApp.mutualAidManager.controllers', []).
    controller('mutualAidCtrl', ['$scope', 'CommunityService', '$http', 'MasterDataService','$location', function ($scope, communityService, $http, masterDataService, $location) {

        $scope.communityLabelList = communityService.getAllCommunityService();
        $scope.tag = masterDataService.getAllDicService({category: '02'});

        $scope.currentPage = 1;
        $scope.totalPage = 0;
        $scope.pages = [];
        $scope.pageSize = 20;
        $scope.communityValue = "";
        var setIn = setInterval(function(){
            if($scope.communityLabelList){
                clearInterval(setIn);
                var selectList = [];
                $scope.communityLabelList.data.forEach(function(item){
                    var a = {};
                    a.name = item.communityName;
                    a.id = item.objId;
                    selectList.push(a);
                });
                new select({data:selectList,id:"community_select",linkId:"select_jing",method:$scope.getList});
            }
        },500);

        $scope.getAllUgc = function (communityId, flag) {
            if (!flag) {
                $scope.currentPage = 1;
            }
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/activity/getAllUgc/' + communityId + '/' + $scope.currentPage, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                //table = 1;
                $scope.allList = data.data.allList;
                $scope.totalPage = data.data.totalPage;
            }).error(function (data) {
            });
        };

        $scope.getList = function (communityId, level) {
            $scope.getAllUgc(communityId, false)
            $scope.communityValue = $('#community_select').val();
        };

        //置顶
        $scope.moveToTop = function (activityId, communityId) {
            var opt = {
                activityId: activityId,
                communityId: communityId
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/activity/moveActivityToTop', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getActivityList(communityId, true);
            }).error(function () {
            });
        };

        $scope.cancelTop = function (activityId, communityId) {
            var opt = {
                activityId: activityId
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/activity/cancelTopActivity', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getActivityList(communityId, true);
            }).error(function () {

            });
        };

        $scope.moveAllToTop = function (id, temp) {

            var obj = temp.target;
            var opt = {
                id: id,
                community: obj.parentNode.dataset.cid
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/activity/moveAllToTop', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getAllUgc(obj.parentNode.dataset.cid, true);
            }).error(function () {
            });
        };

        $scope.cancelAllTop = function (id, temp) {
            var obj = temp.target;
            var opt = {
                id: id
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/activity/cancelTopAll', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getAllUgc(obj.parentNode.dataset.cid, true);
            }).error(function () {

            });
        };

        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;
            $scope.getAllUgc($scope.communityId, true)
        }

        $scope.data = [];
        $scope.toggle = function (ck, objId) {
            !ck ? $scope.data.push(objId) : $scope.data.remove(objId);
        };

        $scope.initTag = function () {
            $scope.data = [];
        };


    }]).controller('mutualAidNeighbourhoodActivityCtrl', ['$scope', 'CommunityService', '$http', 'MasterDataService','$location', function ($scope, communityService, $http, masterDataService,$location) {

        $scope.level = 3;
        $scope.communityLabelList = communityService.getAllCommunityService();
        $scope.tag = masterDataService.getAllDicService({category: '02'});

        $scope.currentPage = 1;
        $scope.totalPage = 0;
        $scope.pages = [];
        $scope.pageSize = 20;

        $scope.onErrorMsg = "";
        $scope.showErrorMsg = false;
        $scope.imgHost = imgHost;
        $scope.arCommunity = {};


        var setIn = setInterval(function(){
            if($scope.communityLabelList){
                clearInterval(setIn);
                var selectList = [];
                $scope.communityLabelList.data.forEach(function(item){
                    var a = {};
                    a.name = item.communityName;
                    a.id = item.objId;
                    selectList.push(a);
                    $scope.arCommunity[item.objId] = item.communityName;
                });
                //new select({data:selectList,id:"community_select",linkId:"select_jing",method:$scope.getList});
                new select({data:selectList,id:"community_select"});
            }
        },1000);


        $scope.exportJoinActivityExcel = function () {
            var commId = $("#community_select")[0].dataset.cId;
            var level =  $scope.level;
            var desc = $scope.description ? $scope.description : '__none';


            if (!(commId || desc != '__none')) {
                alert("小区和搜索内容至少选择一项");
                return;
            }


            var url = 'http://' + backOfficeHost + '/rest/v1.0/backoffice/activity/exportJoinActivity/' + commId + '/' + level + '/' + desc;
            location.href = url;
        };


        $scope.getActivityList = function (communityId, level, description) {

            var commId = $("#community_select")[0].dataset.cId == null ? 'all' : $("#community_select")[0].dataset.cId;
            if($("#community_select").val() == "")commId = "all";

            var desc = description == undefined || description == null || description == '' ? 'all' : description;
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/activity/getBackOfficeActivityList/' + commId + '/' + $scope.currentPage + '/' + level + '/' + desc, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.totalPage = data.data.totalPage;
                var result = data.data.aList;

                $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/getFreshNewsQuestion', {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    $scope.freshQuestion = data.data;

                    result.forEach(function (question) {
                        $scope.freshQuestion.forEach(function (fresh) {
                            if (question.objId == fresh.newsId) {
                                question['isFresh'] = true
                            }
                        });
                    });
                    $scope.activityList = result;
                }).error(function () {
                });

            }).error(function (data) {
            });
        };

        $scope.getActivityList('all', 'undefined', 'all');

        //置顶
        $scope.moveToTop = function (activityId, communityId) {
            var opt = {
                activityId: activityId,
                communityId: communityId
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/activity/moveActivityToTop', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getActivityList(communityId, true);
            }).error(function () {
            });
        };

        $scope.cancelTop = function (activityId, communityId) {
            var opt = {
                activityId: activityId
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/activity/cancelTopActivity', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getActivityList(communityId, true);
            }).error(function () {

            });
        };

        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;
            $scope.getActivityList($scope.communityId, true);
        }

        $scope.data = [];
        $scope.toggle = function (ck, objId) {
            !ck ? $scope.data.push(objId) : $scope.data.remove(objId);
        };

        $scope.initTag = function () {
            $scope.data = [];
        };

        //更新问题
        $scope.updateActivity = function (activity) {

            $scope.onErrorMsg = "";
            $scope.showErrorMsg = false;

            if (!activity.title || activity.title == null || activity.title == '') {
                $scope.onErrorMsg = "请输入标题";
                $scope.showErrorMsg = true;
                return false;
            }
            if (!activity.desc || activity.desc == null || activity.desc == '') {
                $scope.onErrorMsg = "请输入内容";
                $scope.showErrorMsg = true;
                return false;
            }
            if (!activity.deadline || activity.deadline == null || activity.deadline == '') {
            }
            //if(activity.newDeadline){ # if new date is not a proper date type
            //    $scope.onErrorMsg = "Please enter a proper date format";
            //    $scope.showErrorMsg = true;
            //    return false;
            //}
            else{
                activity.newDeadline = activity.deadline;
            }

            var temp = {
                "objId": activity.objId,
                "tag": $scope.data,
                "title": activity.title,
                "desc": activity.desc
                //"deadline": activity.newDeadline
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/activity/backOfficeUpdateActivity', temp, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getActivityList($scope.communityId, true);
            }).error(function () {
            });
        };

        $scope.addActivityToFreshNews = function (activity, title) {
            if (title == null) {
                alert('请输入标题');
                return;
            }
            activity.desc = title;

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/marketing/addActivityToFreshNews', activity, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getActivityList($scope.communityId, true);
            }).error(function () {
            });
        }

        $scope.changeLevel = function (activity, level) {
            console.debug(activity);
            var pushdmsg = "您的话题被设为精华";
            var userRole =  1;
            if(activity.createdBy.userType=="talent") {
                userRole = 2
                pushdmsg = "您的话题被设为精华";
            }
            var input = {
                activityId: activity.objId,
                userId: activity.createdBy.objId,
                userRole: userRole,
                level: level,
                openType: 6,
                //contentId: question.objId,
                //createdBy: question.createdBy.objId,
                desc: pushdmsg,
                tag:'邻里活动'

            };
            console.debug(input);

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/activity/changeActivityLevel', input, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getActivityList($scope.communityId, true);
            }).error(function () {
            });
        }

        //回复
        $scope.repId = "";
        $scope.repPe = false;

        $scope.getRepId = function(temp){
            var obj = temp.target;
            var div =  $(obj.parentNode.parentNode.parentNode).next().children().first();
            $scope.repId = obj.parentNode.dataset.repId;
            div.find(".select-person").val(obj.parentNode.dataset.repName);
            div.find(".rep-post").prop("checked",false);
            div.find(".rep-person").prop("checked",true);
            $scope.repPe = false;
        };
        $scope.repPost = function(temp){
            var obj = temp.target;
            $(obj).next().next().children("input").val("");
            $scope.repId = "";
        };
        $scope.repPerson = function(temp){
            var obj = temp.target;
            if($(obj).next().val() == "") $scope.repPe = true;
        };
        $scope.sendReply = function (question, reply, data2,temp) {
            var obj = temp.target;

            var questionId = question.objId;
            var ommunitycId = question.community.objId;

            if (reply == null || reply.replies.replyDesc == "") {
                alert('回复内容不能为空！');
            } else {
                //小6回复
                //查找小6号码
                var opt = {
                    community :ommunitycId,
                    userType : "service"
                };
                $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/user/getUser', opt, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {

                    var number = "66customerservice";

                    if(data.data.length>0){
                        number = data.data[0].huanxinUserName;
                    }

                    $http.get('http://' + AppHost + '/rest/v1.0/System/userToken/' + number, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (data) {
                        var token = data.data.token;
                        //Questions/postReplyNew/<questionId>/<token>
                        var fdReply = new FormData();
                        fdReply.append('replyDesc', reply.replies.replyDesc);
                        if ($scope.repId)fdReply.append('replyTo', $scope.repId);

                        $http.post('http://' + AppHost + '/rest/v1.0/activity/newActivityReply/' + questionId + '/' + token + "/1", fdReply, {
                            transformRequest: angular.identity,
                            headers: {'Content-Type': undefined}
                        }).success(function (data) {
                            if(data.data == null){alert(data.result.message);return;}
                            var temp = {
                                replyDesc: reply.replies.replyDesc,
                                dateReplied: new Date(),
                                repliedBy: {
                                    nickName: data.data.reply.repliedBy.nickName
                                }
                            };

                            $scope.activityList.forEach(function (question) {
                                if (question.objId == questionId) {
                                    question.replies.push(temp);
                                }
                            });

                            reply.replies.replyDesc = "";

                        }).error(function () {
                        });
                    }).error(function () {
                    });

                }).error(function () {
                });
            }
            $("#reply").val("");
        };

    }]).directive('mutau', function () {
        return {
            restrict: 'E',
            //scope: {
            //    numPages: '=',
            //    currentPage: '=',
            //    onSelectPage: '&'
            //},
            template: '',
            replace: true,
            link: function (scope, element, attrs) {
                scope.$watch('currentPage', function (value) {
                    scope.pages = [];
                    for (var i = value - 5 > 0 ? value - 5 : 1; i <= (value + 5 > scope.totalPage ? scope.totalPage : value + 5); i++) {
                        scope.pages.push(i);
                    }
                });
                scope.$watch('totalPage', function (value) {
                    scope.pages = [];
                    for (var i = scope.currentPage - 5 > 0 ? scope.currentPage - 5 : 1; i <= (scope.currentPage + 5 > value ? value : scope.currentPage + 5); i++) {
                        scope.pages.push(i);
                    }
                });

                scope.isActive = function (page) {
                    return scope.currentPage === page;
                };
                scope.selectPage = function (page) {
                    if (!scope.isActive(page)) {
                        scope.currentPage = page;
                        scope.onSelectPage(page);
                    }
                };
                scope.selectPrevious = function () {
                    if (!scope.noPrevious()) {
                        scope.selectPage(scope.currentPage - 1);
                    }
                };
                scope.selectNext = function () {
                    if (!scope.noNext()) {
                        scope.selectPage(scope.currentPage + 1);
                    }
                };
                scope.noPrevious = function () {
                    return scope.currentPage == 1;
                };
                scope.noNext = function () {
                    return scope.currentPage == scope.totalPage;
                };
            }
        };
    });